import React, { useEffect } from 'react';
import { append } from '../utils';

/**
 * 喝水问题：
 * 四个空瓶换一瓶水，两个盖子换一瓶水
 */
const BOTTLE_TO_DRINKS = 4;
const CAP_TO_DRINKS = 2;

/**
 * 整除算法
 *
 * @param {*} dividend 被除数
 * @param {*} divisor 除数
 * @returns {*} { quotient: number, remainder: number }
 */
function integerDivide(dividend, divisor) {
  return {
    quotient: Math.floor(dividend / divisor),
    remainder: dividend % divisor,
  };
}

/**
 * 喝掉 N 瓶水得到的空瓶和盖的数量
 *
 * @param {*} drinks 带水的瓶子
 */
function cost() {
  let total = 0;
  return function (drinks) {
    const symbol = total === 0 ? '' : '又';
    append(
      `郭东临${symbol}喝掉了 ${drinks} 瓶水，共 ${(total += drinks)} 瓶了`,
    );
    return { bottles: drinks, caps: drinks };
  };
}

/**
 * 交换规则
 *
 * @param {*} bottles 空瓶数量
 * @param {*} caps 盖子数量
 * @returns {*} { bottles: number, caps: number, drinks: number }
 */
function exechange(bottles, caps) {
  const { quotient: bottleDRINKSCount, remainder: bottleLeft } = integerDivide(
    bottles,
    BOTTLE_TO_DRINKS,
  );
  const { quotient: capDRINKSCount, remainder: capsLeft } = integerDivide(
    caps,
    CAP_TO_DRINKS,
  );
  const drinks = bottleDRINKSCount + capDRINKSCount;
  if (drinks > 0) {
    append(
      `用 ${bottles} 个空瓶子和 ${caps} 个盖子交换了 ${drinks} 瓶水，还剩下 ${bottleLeft} 个空瓶子和 ${capsLeft} 个盖子`,
    );
  }
  return {
    drinks,
    bottleLeft,
    capsLeft,
  };
}

function main() {
  let drinks = 5;
  let bottles = 0;
  let caps = 0;
  const drink = cost();

  while (drinks > 0 || bottles >= BOTTLE_TO_DRINKS || caps >= CAP_TO_DRINKS) {
    const { bottles: b, caps: c } = drink(drinks);
    const { drinks: d, bottleLeft, capsLeft } = exechange(
      bottles + b,
      caps + c,
    );
    bottles = bottleLeft;
    caps = capsLeft;
    drinks = d;
  }
}

export default function DrinkDemo() {
  useEffect(main, null);
  return (
    <div id="content">
      <h1>喝水问题</h1>
      <h2>
        {BOTTLE_TO_DRINKS}
        个空瓶换一瓶水，
        {CAP_TO_DRINKS}
        个盖子换一瓶水
      </h2>
    </div>
  );
}
